package com.servlet.control;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.bean.TeacherCourse;
import com.jdbc.util.DBUtilForTeacher;
import com.jdbc.util.TimePlanUtil;

@WebServlet(name = "TeacherCourseListServlet", urlPatterns = "/TeacherCourseListServlet")
public class TeacherCourseListServlet extends HttpServlet {
	public TeacherCourseListServlet() {
		super();
	}

	public void destroy() {
		super.destroy();
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response) {
		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) {
		try {
			request.setCharacterEncoding("utf-8");
			response.setContentType("text/html;charset=utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		List<TeacherCourse> teacherCourseList = new ArrayList<>();

		DBUtilForTeacher db = new DBUtilForTeacher();
		db.getConn();

		ResultSet rs = db.getResult("select * from course");

		try {
			while (rs.next()) {
				TeacherCourse teacherCourse = new TeacherCourse();

				teacherCourse.setCourseID(rs.getString("course_id"));
				teacherCourse.setCourseName(rs.getString("course_name"));
				teacherCourse.setTeacher(rs.getString("teacher"));
				teacherCourse.setPoint(rs.getInt("point"));
				teacherCourse.setTime_1(TimePlanUtil.transform(rs.getString("time_1")));
				teacherCourse.setTime_2(TimePlanUtil.transform(rs.getString("time_2")));
				teacherCourse.setLocation(rs.getString("location"));
				teacherCourse.setLimited(rs.getInt("limited"));

				ResultSet pp =
						db.getResult(
								"select count(*) total from elective where course_id="
										+ teacherCourse.getCourseID());
				int num = 0;
				if (pp.next()) {
					num = pp.getInt("total");
				}
				teacherCourse.setPopulation(num);

				teacherCourseList.add(teacherCourse);
			}

			request.setAttribute("teacherCourseList", teacherCourseList);

			request.getRequestDispatcher("/jsp/showTeacherCourse.jsp").forward(request, response);
		} catch (SQLException | ServletException | IOException e) {
			e.printStackTrace();
		} finally {
			db.release();
		}
	}
}
